'use strict';

const Controller = require('../core/base_controller');

class UserController extends Controller {
  async login() {
    const { ctx } = this;
    try {
      const res = await ctx.service.user.login();
      this.success(res)
    } catch (err) {
      this.error(err.message)
    }
  }
  async register() {
    const { ctx } = this;
    try {
      const res = await ctx.service.user.register();
      this.success(res)
    } catch (err) {
      this.error(err.message)
    }
  }
  async refresh() {
    // 刷新token
    // 获取旧token 返回新token
    const { ctx, app } = this;
    const { authorization } = ctx.request.header;
    const { token } = authorization.split(' ')[1]
    const jwt = require('jsonwebtoken')
    const user = jwt.verify(token, app.config.keys);
    const newToken = jwt.sign({ id: user.id, nickname: user.nickname }, app.config.keys, { expiresIn: '2h' })
    try {
      this.success({
        token: newToken,
        expiresIn: Date.now() + (2 * 60 * 60 * 1000)
      })
    } catch (err) {
      this.error(err.message)
    }
  }
}

module.exports = UserController;
